import dayjs from "dayjs";
import { getAppEnvConfig } from "./env";
import fs from "vite-plugin-fs/browser";
import path from "path-browserify";

export default class LogsController {
  static LOGS_INSTANCE: LogsController;

  static factory() {
    if (!this.LOGS_INSTANCE) {
      this.LOGS_INSTANCE = new this();
    }
    return this.LOGS_INSTANCE;
  }

  private FILE_BASE_PATH: string = "";

  constructor() {
    let { logBasePath } = getAppEnvConfig();

    
    if (logBasePath) {
      this.FILE_BASE_PATH = logBasePath;
    }
  }

  //写入logs
  writeLogs(describe: string) {
    try {
      let val: string = '';
      fs.readFile(this.joinFileName())
        .then((res) => { val = res;})
        .catch(()=>{})
        .finally(() => {
        val && (val += "\r\n")
          val += `${dayjs().format("HH:mm:ss")}：${describe}`;
          fs.writeFile(this.joinFileName(), val);
        });
    } catch {
    
    }
  }

  //拼接文件地址
  joinFileName() {
    return path.join(
      __APP_INFO__.root,
      this.FILE_BASE_PATH  + dayjs().format("YYYY-MM-DD") + "_error_logs.txt"
    );
  }
}
